#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "h/stack.h"

static void copyItemToNode(Item, Node *);

void InitializeStack(Stack * ps)
{
    ps->top = NULL;
    ps->size = 0;
}

bool StackIsFull(Stack * ps)
{
    return ps->size == STACKMAX;
}

bool StackIsEmpty(Stack * ps)
{
    return ps->size == 0;
}

int StackCountItem(Stack * ps)
{
    return ps->size;
}

bool AddStackItem(Item item, Stack * ps)
{
    Node * newn;
    if (StackIsFull(ps))
        return false;

    newn = (Node *)malloc(sizeof(Node));
    if (NULL == newn)
    {
        fprintf(stderr, "create node failed.");
        exit(EXIT_FAILURE);
    }

    copyItemToNode(item, newn);
    newn->prev = NULL;

    newn->prev = ps->top;
    ps->top = newn;

    ++ps->size;

    return true;
}

bool OutStackItem(Item * item, Stack * ps)
{
    Node * pold;

    if (StackIsEmpty(ps))
        return false;

    pold = ps->top;

    *item = ps->top->item;
    ps->top = ps->top->prev;
    --ps->size;

    free(pold);

    return true;
}

void EmptyTheStack(Stack * ps)
{
    Node * out;
    while (ps->top)
    {
        out = ps->top->prev;
        free(ps->top);
        ps->top = out;
    }

}

static void copyItemToNode(Item item, Node * node)
{
    node->item = item;
}
